<template>
  <div class="box">
    <div class="table">
      <p :style="{ textAlign: 'right', marginBottom: '5px' }">
        <a-button
          v-if="!specialIds.includes(shipId) && complete === 0"
          size="small"
          @click="action('add')"
          type="primary"
          link
          ><template #icon><PlusOutlined /></template> 添加</a-button
        >
      </p>
      <a-table
        :dataSource="state.tableData"
        :columns="state.columns"
        :pagination="{
          total: state.total,
          pageSize,
          showSizeChanger: false,
          size: 'normal',
        }"
        bordered
        :scroll="{ x: 1200 }"
        size="small"
        rowKey="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key === 'action'">
            <a-space :size="5" spacer="|">
              <DeleteBtn
                title="确认删除?"
                label="删除"
                @onDelete="action('remove', record)"
              />
              <a-button type="link" @click="action('edit', record)" link
                ><template #icon>
                  <EditOutlined />
                </template>
                编辑</a-button
              >
              <a-button
                v-if="workflow?.value === '9'"
                type="link"
                @click="action('sync', record)"
                link
                ><template #icon>
                  <thunderbolt-outlined />
                </template>
                电量</a-button
              >
            </a-space>
          </template>
          <template v-else-if="column.key === 'mfid'">
            {{ getMfName(text) }}
          </template>
        </template>
        <template v-if="state.innerColumns" #expandedRowRender="{ record }">
          <p :style="{ textAlign: 'right', marginBottom: '4px' }">
            <a-button
              v-if="!specialIds.includes(shipId) && complete === 0"
              @click="innerAction('add', { pid: record.id })"
              type="text"
              ><template #icon>
                <PlusOutlined />
              </template>
              添加</a-button
            >
          </p>
          <a-table
            :columns="state.innerColumns"
            :data-source="record.inner"
            :pagination="false"
            rowKey="id"
            bordered
            size="small"
          >
            <template
              #bodyCell="{
                column: innerColumn,
                record: innerRecord,
                text: innerText,
              }"
            >
              <template v-if="innerColumn.key === 'action'">
                <a-space :size="10" spacer="|">
                  <DeleteBtn
                    title="确认删除?"
                    type="text"
                    @onDelete="innerAction('remove', innerRecord)"
                  />
                  <a-button
                    type="text"
                    @click="
                      innerAction('edit', { ...innerRecord, pid: record.id })
                    "
                    ><template #icon> <EditOutlined /> </template
                  ></a-button>
                  <a-button
                    v-if="['0', '8'].includes(workflow?.value)"
                    type="text"
                    @click="
                      innerAction('sync', { ...innerRecord, pid: record.id })
                    "
                    link
                    ><template #icon>
                      <thunderbolt-outlined />
                    </template>
                  </a-button>
                </a-space>
              </template>
              <template v-else-if="innerColumn.key === 'mfid'">
                {{ getMfName(innerText) }}
              </template>
            </template>
          </a-table>
        </template>
      </a-table>
    </div>
    <FormModal
      :formConfig="state.formConfig"
      @submit="submit"
      ref="dialogRef"
    />
    <FormModal
      v-if="state.innerFormConfig"
      :formConfig="state.innerFormConfig"
      ref="dialogInnerRef"
      @submit="innerSubmit"
    />
  </div>
</template>

<script setup>
import {
  onBeforeMount,
  getCurrentInstance,
  reactive,
  ref,
  computed,
  watch,
} from "vue";
import _ from "lodash";
import FormModal from "@/components/FormModal.vue";
import DeleteBtn from "@/components/DeleteBtn.vue";
import {
  workColumns,
  innerColumns,
  workFormItems,
  innerFormItems,
} from "@/utils/shipflow/flow.js";
import * as ysflow from "@/utils/shipflow/ysflow.js";
import * as yyflow from "@/utils/shipflow/yyflow.js";

const pageSize = 15;

const props = defineProps(["orderId", "workflow", "shipId", "complete"]);
const { proxy } = getCurrentInstance();
const state = reactive({
  mfList: [],
  columns: [],
  formConfig: {
    title: "表单",
    items: [],
  },
  tableData: [],
  total: 0,
  innerColumns: null,
  innerFormConfig: null,
});
const dialogRef = ref();
const dialogInnerRef = ref();

const apis = {
  normal: {
    0: "/workflow_ship_cut",
    1: "/workflow_ship_old",
    2: "/workflow_ship_weld",
    3: "/workflow_machine_pipe",
    4: "/workflow_towship_oil",
    "5-0": "/workflow_other_oil_ship",
    "5-1": "/workflow_other_oil_car",
    "6-0": "/workflow_paint_ship",
    "6-1": "/workflow_paint_house",
    "7-0": "/workflow_ship_sand",
    "7-1": "/workflow_house_sand",
    8: "/workflow_water_clean",
    9: "/workflow_electric_box",
  },
  special: {
    0: "/workflow_special/ship_cut",
    1: "/workflow_special/ship_old",
    2: "/workflow_special/ship_weld",
    3: "/workflow_special/machine_pipe",
    4: "/workflow_special/towship_oil",
    "5-0": "/workflow_special/other_oil_ship",
    "5-1": "/workflow_special/other_oil_car",
    "6-0": "/workflow_special/paint_ship",
    "6-1": "/workflow_special/paint_house",
    "7-0": "/workflow_special/ship_sand",
    "7-1": "/workflow_special/house_sand",
    8: "/workflow_special/water_clean",
    9: "/workflow_special/electric_box",
  },
};

onBeforeMount(() => {
  proxy.$axios.get("/electric/common/list").then(({ success, data }) => {
    if (success) {
      state.mfList = data.map((o) => ({
        label: o.name,
        value: o.mfid,
      }));
    }
  });
});

const ysIds = [10000001, 10000002];
const yyIds = [10000003, 10000004];
const specialIds = [...ysIds, ...yyIds];

const getList = async (page) => {
  const { value } = props.workflow;
  let url = apis.normal[value];
  if (specialIds.includes(props.shipId)) {
    url = apis.special[value];
  }
  if (url) {
    const { success, data } = await proxy.$axios.get(`${url}/list`, {
      params: { pageNumber: page, pageSize, repairId: props.orderId },
    });
    if (success) {
      const { content, totalElements } = data;
      state.tableData = content;
      state.total = totalElements;
    }
  }
};

watch(
  () => [props.workflow, props.shipId],
  ([_workflow, _shipId]) => {
    if (_workflow && _shipId) {
      const { label, value } = _workflow;
      if (specialIds.includes(_shipId)) {
        let flow = null;
        if (ysIds.includes(_shipId)) {
          flow = ysflow;
        } else if (yyIds.includes(_shipId)) {
          flow = yyflow;
        }
        let _columns = [];
        let _innerColumns = null;
        if (flow) {
          if (flow.workColumns[value]) {
            _columns = _.map(flow.workColumns[value], (column) => ({
              ...column,
              width: 180,
              ellipsis: true,
            }));
          }
          if (flow.innerColumns[value]) {
            _innerColumns = _.map(flow.innerColumns[value], (column) => ({
              ...column,
              ellipsis: true,
            }));
            if (!props.complete) {
              _innerColumns.push({
                title: "操作",
                dataIndex: "action",
                key: "action",
                fixed: "right",
                width: 180,
                align: "center",
              });
            }
          }
        }
        state.columns = _columns;
        state.innerColumns = _innerColumns;
      } else {
        let _columns = [];
        if (workColumns[value]) {
          _columns = _.map(workColumns[value], (column) => ({
            ...column,
            width: 180,
            ellipsis: true,
          }));
          if (props.complete === 0) {
            _columns.push({
              title: "操作",
              key: "action",
              fixed: "right",
              width: 280,
              align: "center",
            });
          }
        }
        state.columns = _columns;

        let _innerColumns = null;
        if (innerColumns[value]) {
          _innerColumns = _.map(innerColumns[value], (column) => ({
            ...column,
            ellipsis: true,
          }));
          if (props.complete === 0) {
            _innerColumns.push({
              title: "操作",
              key: "action",
              width: 140,
              align: "center",
            });
          }
        }
        state.innerColumns = _innerColumns;

        // 非特殊船舶才允许构建表单
        state.formConfig = {
          title: label,
          items: workFormItems[value] || [],
        };
        if (innerFormItems[value]) {
          state.innerFormConfig = {
            title: `${label}子表单`,
            items: innerFormItems[value],
          };
        } else {
          state.innerFormConfig = null;
        }
      }
      getList(1);
    }
  },
  { immediate: true }
);

const handleTableChange = ({ current }) => {
  getList(current);
};

const action = (type, record) => {
  if (type === "add") {
    const formItem = _.find(state.formConfig.items, { name: "mfid" });
    if (formItem) {
      formItem.options = state.mfList;
    }
    dialogRef.value.handleOpenForm({});
  } else if (type === "edit") {
    const formItem = _.find(state.formConfig.items, { name: "mfid" });
    if (formItem) {
      formItem.options = state.mfList;
    }

    dialogRef.value.handleOpenForm({ ...record });
  } else if (type === "remove") {
    const { value } = props.workflow;
    const url = apis.normal[value];
    const apiUrl = `${url}/${record.id}`;
    proxy.$axios.delete(apiUrl).then(({ success }) => {
      if (success) {
        getList(1);
      }
    });
  } else if (type === "sync") {
    if (!record.mfid) {
      proxy.$message.error("请先选择电表");
      return;
    }
    let syncApi = null;
    if (props.workflow.value === "9") {
      syncApi = `/workflow_electric_box/child/sync/${record.id}`;
    }
    if (syncApi) {
      proxy.$axios.get(syncApi).then(({ success, data }) => {
        if (success) {
          const one = _.find(state.tableData, { id: record.id });
          one.power = data.power;

          proxy.$message.success("电量同步成功");
        }
      });
    }
  }
};

const submit = (values) => {
  const { value } = props.workflow;
  let method = "post";
  let url = apis.normal[value];
  if (values.id) {
    method = "put";
    url = `${url}/${values.id}`;
  }
  if (value === "9") {
    values.electricBoxNo = getMfName(values.mfid);
  }
  values.shipRepairId = props.orderId;
  proxy.$axios({ method, data: values, url }).then(({ success }) => {
    if (success) {
      dialogRef.value.cancel();
      proxy.$message.success("提交成功");
      getList(1);
    }
  });
};

const innerAction = (type, record) => {
  if (type === "add") {
    const formItem = _.find(state.innerFormConfig.items, { name: "mfid" });
    if (formItem) {
      formItem.options = state.mfList;
    }

    dialogInnerRef.value.handleOpenForm(record);
  } else if (type === "edit") {
    const formItem = _.find(state.innerFormConfig.items, { name: "mfid" });
    if (formItem) {
      formItem.options = state.mfList;
    }

    dialogInnerRef.value.handleOpenForm({ ...record });
  } else if (type === "remove") {
    const { value } = props.workflow;
    const url = apis.normal[value];
    const apiUrl = `${url}/child/${record.id}`;
    proxy.$axios.delete(apiUrl).then(({ success }) => {
      if (success) {
        proxy.$message.success("删除成功");
        const all = [...state.tableData];
        const one = _.find(all, { id: record.pid });
        const _list = [...one.inner];
        one.inner = _.filter(_list, (o) => o.id !== record.id);
        state.tableData = all;
      }
    });
  } else if (type === "sync") {
    if (!record.mfid) {
      proxy.$message.error("请先选择电表");
      return;
    }

    let syncApi = null;
    if (props.workflow.value === "8") {
      syncApi = `/workflow_water_clean/child/sync/${record.id}`;
    } else if (props.workflow.value === "0") {
      syncApi = `/workflow_ship_cut/child/sync/${record.id}`;
    }
    if (syncApi) {
      proxy.$axios.get(syncApi).then(({ success, data }) => {
        if (success) {
          proxy.$message.success("电量同步成功");

          const one = _.find(state.tableData, { id: record.pid });
          if (one) {
            const inner = _.find(one.inner, { id: record.id });
            if (inner) {
              inner.totalPower = data.totalPower;
            }
          }
        }
      });
    }
  }
};

const innerSubmit = (values) => {
  const { value } = props.workflow;
  let method = "post";
  let url = `${apis.normal[value]}/child`;
  if (values.id) {
    method = "put";
    url = `${url}/${values.id}`;
  }
  if (value === "0") {
    values.deviceNo = getMfName(values.mfid);
  } else if (value === "8") {
    values.device = getMfName(values.mfid);
  }

  proxy.$axios({ method, data: values, url }).then(({ success, data }) => {
    if (success) {
      dialogInnerRef.value.cancel();
      proxy.$message.success("提交成功");

      const all = [...state.tableData];
      const one = _.find(all, { id: values.pid });
      if (method === "put") {
        const i = _.findIndex(one.inner, { id: values.id });
        one.inner[i] = values;
      } else {
        one.inner = [...one.inner, data];
      }
      state.tableData = all;
    }
  });
};

const getMfName = (mfid) => {
  const one = _.find(state.mfList, { value: mfid });
  return one ? one.label : null;
};
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;

  .table {
    width: 100%;
    padding: 2px;
    overflow-y: auto;
  }
}
</style>
